package com.hkbigdata.springbootdi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hkbigdata.springbootdi.bean.*;
import com.hkbigdata.springbootdi.mapper.DiMapper;
import com.hkbigdata.springbootdi.mapper.ESDao;
import com.hkbigdata.springbootdi.service.DiService;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * @author liuanbo
 * @creat 2024-12-06-10:54
 * @see 2194550857@qq.com
 */
@Service
public class DiServiceImpl implements DiService {

    @Autowired
    DiMapper diMapper;

    @Override
    public ResponData queryOrderStatus(String dt) {
        List<OrderStatus> orderStatuses = diMapper.queryOrderStatus(dt);
        System.out.println(JSON.toJSONString(orderStatuses));

       /* //定义最外层json
        JSONObject result = new JSONObject();
        JSONObject datajson = new JSONObject();

        //定义seriesjson数组
        ArrayList<JSONObject> seriesjson = new ArrayList<>();
        ArrayList<String> categories = new ArrayList<>();

        JSONObject orderJSON = new JSONObject();
        JSONObject refundJSON = new JSONObject();

        ArrayList<Integer> orderData = new ArrayList<>();
        ArrayList<Integer> refundData = new ArrayList<>();

        //遍历数据获取到时间，退单，订单数
        for (OrderStatus orderStatus : orderStatuses) {
            categories.add(orderStatus.getTime());
            orderData.add(orderStatus.getOrderConut());
            refundData.add(orderStatus.getRefundConut());
        }

        orderJSON.put("name", "订单数");
        orderJSON.put("data", orderData);

        refundJSON.put("name", "退款数");
        refundJSON.put("data", refundData);

        seriesjson.add(orderJSON);
        seriesjson.add(refundJSON);

        datajson.put("series", seriesjson);
        datajson.put("categories", categories);

        result.put("data", datajson);
        result.put("msg", "success");
        result.put("status", 0);*/
        ArrayList<String> categories = new ArrayList<>();
        ArrayList<Integer> orderData = new ArrayList<>();
        ArrayList<Integer> refundData = new ArrayList<>();
        for (OrderStatus orderStatus : orderStatuses) {
            categories.add(orderStatus.getTime());
            orderData.add(orderStatus.getOrderConut());
            refundData.add(orderStatus.getRefundConut());

        }
        SeriesData<Integer> orderDataseriesData = new SeriesData<>("新增订单量", orderData);
        SeriesData<Integer> refundDataseriesData = new SeriesData<>("退款订单量", refundData);

        ResponData responData = new ResponData("", 0, categories, Arrays.asList(orderDataseriesData, refundDataseriesData));

        return responData;
    }

    @Autowired
    RedisTemplate<String, String> redisTemplate;

    @Value("${di.redis.key}")
    String rediskey;


    @Override
    public ResponData queryBrandScore() {
        Set<ZSetOperations.TypedTuple<String>> res = redisTemplate.opsForZSet().reverseRangeWithScores(rediskey, 0, 5);
        //res.forEach(System.out::println);
        /*  JSONObject result = new JSONObject();
        JSONObject datajson = new JSONObject();
        ArrayList<JSONObject> seriesjson = new ArrayList<>();
        JSONObject phonejson = new JSONObject();
        ArrayList<Double> phonedata = new ArrayList<>();
        ArrayList<String> categories = new ArrayList<>();
        res.forEach(e -> {
            categories.add(e.getValue());
            phonedata.add(e.getScore());
        });

        phonejson.put("name", "手机品牌");
        phonejson.put("data", phonedata);

        seriesjson.add(phonejson);

        datajson.put("series", seriesjson);
        datajson.put("categories", categories);

        result.put("data", datajson);
        result.put("msg", "success");
        result.put("status", 0);*/
        ArrayList<Double> phonedata = new ArrayList<>();
        ArrayList<String> categories = new ArrayList<>();

        for (ZSetOperations.TypedTuple<String> e : res) {
            categories.add(e.getValue());
            phonedata.add(e.getScore());
        }

        SeriesData<Double> seriesData = new SeriesData<>("手机品牌", phonedata);
        System.out.println(JSONObject.toJSON(seriesData));

        ResponData responData = new ResponData("", 0, categories, Arrays.asList(seriesData));
        return responData;
    }

    @Override
    public ResponData queryCkSales() {
        List<SaleBrand> saleBrands = diMapper.querySaleBrand();
        ArrayList<Double> saleamount = new ArrayList<>();
        ArrayList<String> categories = new ArrayList<>();

        for (SaleBrand saleBrand : saleBrands) {
            categories.add(saleBrand.getBrand());
            saleamount.add(saleBrand.getAmount());
        }
        SeriesData<Double> seriesData = new SeriesData<>("销售金额", saleamount);

        return new ResponData("", 0, categories, Arrays.asList(seriesData));
    }

    @Override
    public ResponData queryCkSalesTotal() {
        List<SaleBrandTotal> saleBrandTotals = diMapper.querySaleBrandTotal();
        ArrayList<Double> todaysaleamount = new ArrayList<>();
        ArrayList<Double> yestodaysaleamount = new ArrayList<>();
        ArrayList<Double> passweeksaleamount = new ArrayList<>();
        ArrayList<String> categories = new ArrayList<>();

        saleBrandTotals.forEach(e -> {
            System.out.println(e.getBrand());
            categories.add(e.getBrand());
            todaysaleamount.add(e.getTodayamount());
            yestodaysaleamount.add(e.getYestodayamount());
            passweeksaleamount.add(e.getPassweekamount());

        });
        SeriesData<Double> todayseries = new SeriesData<>("今日销量", todaysaleamount);
        SeriesData<Double> yestodayseries = new SeriesData<>("昨天销量", yestodaysaleamount);
        SeriesData<Double> passweekseries = new SeriesData<>("上周销量", passweeksaleamount);


        return new ResponData("", 0, categories, Arrays.asList(todayseries, yestodayseries, passweekseries));
    }

    @Autowired
    ESDao esDao;

    @Override
    public JSONObject queryEsSource() {
        //1.构建聚合条件
        TermsAggregationBuilder aggs = AggregationBuilders.terms("agg_source").field("source").size(10);

        SearchHits<Customer> searchHits = esDao.queryFromEs(aggs, Customer.class);

        //2.获取聚合结果
        Aggregations aggregations = searchHits.getAggregations();
        //3.获取分组后的数据
        Terms terms = aggregations.get("agg_source");
        //4.获取分桶数据
        List<? extends Terms.Bucket> buckets = terms.getBuckets();

        ArrayList<JSONObject> datajson = new ArrayList<>();
        //5.从buckets里面获取数据遍历json，对象赋值
        for (Terms.Bucket bucket : buckets) {
            JSONObject dataPJ = new JSONObject();
            dataPJ.put("name", bucket.getKeyAsString());
            dataPJ.put("value", bucket.getDocCount());
            datajson.add(dataPJ);
        }

        //6.创建返回值的json
        JSONObject result = new JSONObject();
        result.put("data", datajson);
        result.put("msg", "");
        result.put("status", 0);
        return result;
    }


    @Override
    public JSONObject queryEsProfeesionSex() {
        TermsAggregationBuilder agg = AggregationBuilders.terms("agg_profeesion").field("profession").size(10)
                .subAggregation(AggregationBuilders.terms("agg_sex").field("sex").size(2));

        SearchHits<Customer> searchHits = esDao.queryFromEs(agg, Customer.class);

        Aggregations aggregations = searchHits.getAggregations();
        Terms terms = aggregations.get("agg_profeesion");
        //最外层的桶
        List<? extends Terms.Bucket> buckets = terms.getBuckets();
        ArrayList<Long> manarr = new ArrayList<>();
        ArrayList<Long> womanarr = new ArrayList<>();
        ArrayList<String> categories = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            categories.add(bucket.getKeyAsString());
            Aggregations subagg = bucket.getAggregations();
            Terms subterms = subagg.get("agg_sex");
            List<? extends Terms.Bucket> subbuckets = subterms.getBuckets();
            for (Terms.Bucket subbucket : subbuckets) {
                if (subbucket.getKeyAsString().equals("男")) {
                    long man = subbucket.getDocCount() * 100 / bucket.getDocCount();
                    manarr.add(man);
                    womanarr.add(100 - man);
                }
            }
        }

        SeriesData<Long> manseries = new SeriesData<>("男", manarr);
        SeriesData<Long> womanseries = new SeriesData<>("女", womanarr);
        String s1 = JSON.toJSONString(manseries);
        String s2 = JSON.toJSONString(womanseries);
        JSONObject manjson = JSONObject.parseObject(s1);
        JSONObject womanjson = JSONObject.parseObject(s2);
        manjson.put("unit", "%");
        womanjson.put("unit", "%");

        ArrayList<JSONObject> seriesjson = new ArrayList<>();
        seriesjson.add(manjson);
        seriesjson.add(womanjson);

        JSONObject datajson = new JSONObject();
        datajson.put("categories", categories);
        datajson.put("series", seriesjson);
        JSONObject result = new JSONObject();
        result.put("data", datajson);
        result.put("msg", "");
        result.put("status", 0);

        return result;
    }

    @Override
    public JSONObject queryCkProvinceSales(String province) {
        Double amount = diMapper.querySaleAmount(province);
        JSONObject result = new JSONObject();
        Double percent = 0d;
        if (amount > 1000000) {
            percent = 100d;
        } else {
            percent = amount * 100 / 1000000d;
        }
        result.put("data", percent);
        result.put("msg", "");
        result.put("status", 0);
        return result;
    }

    @Override
    public JSONObject queryCkProvinceOrderAndSales() {
        List<ProvinceData> provinceData = diMapper.queryProvinceData();
        JSONObject datajson = new JSONObject();
        datajson.put("sizeValueName", "销售额");
        datajson.put("valueName", "下单数");
        datajson.put("mapData", provinceData);
        JSONObject result = new JSONObject();
        result.put("data", datajson);
        result.put("msg", "");
        result.put("status", 0);
        return result;
    }

    @Autowired
    KafkaTemplate<String, String> kafkaTemplate;

    @Value("${di.kafka.topic}")
    private String topic;

    @Override
    public void pushLogToKafka(String log) {
        System.out.println("推送日志到kafka" + log);
        kafkaTemplate.send(topic, log);
    }
}
